package com.topisv.tms.web.focus;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.ShippedBox;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.shipped.ShippedBoxService;
import com.topisv.tms.service.shipped.ShippedBoxSkusService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.utils.enums.StatusEnums;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;

@Controller
@RequestMapping({ "/pickBackupTask" })
public class PickBackupTaskController {

	private static final Logger logger = LoggerFactory.getLogger(PickBackupTaskController.class);
	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private WorkTaskItemService workTaskItemService;
	@Autowired
	private ShippedBoxSkusService shippedBoxSkusService;
	@Autowired
	private ShippedBoxService shippedBoxService;

	/**
	 * 导向边拣货边装箱页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toPickPage/{backupTaskCode}", method = RequestMethod.GET)
	public String toPickPage(
			@PathVariable("backupTaskCode") String backupTaskCode, Model model) {
		BackupTask backupTask = null;
		int noBoxNumber = 0;
		int boxNumber = 0;
		List<ShippedBox> shippedBoxs = null;
		ShiroUser user=getShiroUser();
		Map<String, Integer> allSkuMaps=null;
		try {
			// 任务信息
			backupTask = this.backupTaskService.setJobuuid(backupTaskCode, user.jobuuid,"pickBox");
			if(backupTask==null){
				return "redirect:/focusBackupTask/backupTaskLists";
			}
			model.addAttribute("task", backupTask);
			allSkuMaps = shippedBoxSkusService.getShippedBoxSkus(backupTaskCode);// 未装箱的商品
			shippedBoxs = shippedBoxService.findByBatchCode(backupTaskCode);// 装箱的商品
			for (String key : allSkuMaps.keySet()) {
				noBoxNumber += allSkuMaps.get(key);
			}
			for (ShippedBox obj : shippedBoxs) {
				boxNumber += obj.getSkuQty();
			}
			// 将sku转化为大写
			model.addAttribute("shippedBoxs", shippedBoxs);
			model.addAttribute("noBoxNumber", noBoxNumber);//
			model.addAttribute("boxNumber", boxNumber);//
			model.addAttribute("allSkuMaps", allSkuMaps);// 已经扫描但是没有装箱的商品
			// 拣货任务项
			Map<String, Object> param1 = new HashMap<String, Object>();
			param1.put("taskCode", backupTaskCode);
			List<WorkTaskItem> taskItemList = this.workTaskItemService.loadByParam(param1);
			model.addAttribute("taskItemList", taskItemList);

		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/gather/pickBackupTask";
	}


	/**
	 * 拣货
	 * 
	 * @param taskItemId
	 *            拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxPick")
	public void ajaxPick(ServletRequest request, HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();

			Long taskItemId = Long.valueOf(request.getParameter("taskItemId"));
			String sku = request.getParameter("sku");

			// 拣货
			String msg = this.backupTaskService.pick(taskItemId, sku,"pickBox");
			json.put("status", msg);

		} catch (Exception e) {
			
			json.put("status", "error");
			json.put("content", e.getMessage());
			logger.error("error",e);
		}
		out.print(json.toString());
	}

	/**
	 * 完成拣货任务
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCompletePickTask")
	@ResponseBody
	public String ajaxCompletePickTask(ServletRequest request,
			HttpServletResponse response) {
		try {
			Long taskId = Long.valueOf(request.getParameter("taskId") + "");
			this.backupTaskService.completePickTask(taskId);
			return "true";
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 商品封箱子
	 * @param backupTaskCode
	 * @param boxCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxCreateBox")
	public void ajaxPick(@RequestParam(value="backupTaskCode") String backupTaskCode,@RequestParam(value="boxCode") String boxCode, HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		ShippedBox shippedBox = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			shippedBox=this.shippedBoxService.findByBoxCode(boxCode);
			if(shippedBox!=null){
				json.put("status", 0);
				json.put("content", "该箱子编码已经存在");
				out.print(json.toString());
				return;
			}
			
		     //装箱
			 shippedBox=backupTaskService.excuteShippedBox(backupTaskCode, boxCode);
			BackupTask task=this.backupTaskService.findByBackupTaskCode(backupTaskCode);
			json.put("content", shippedBox);
			json.put("status", 1);
			if("finish".equals(task.getStatus())){
				////自动推送出库批次
//				SynchroShippedBatchQueue.putSendMessageQueue("createBatch"+StatusEnums.split.getStatus()+backupTaskCode);
			}
		} catch (Exception e) {
			
			json.put("status", "error");
			json.put("content", e.getMessage());
			logger.error("error",e);
		}
		out.print(json.toString());
	}
	
	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

}
